package com.qingcheng.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.goods.Goods;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.service.goods.SpuService;
import com.qingcheng.util.RestHighLevelClientFactory;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.List;

/**
 * 消息监听类,删除索引库中的sku数据
 */
public class MessageConsumer4 implements MessageListener {
    @Reference
    private SpuService spuService;
    @Value("${host}")
    private String host;
    @Value("${port}")
    private int port;

    @Override
    public void onMessage(Message message) {
        RestHighLevelClient restHighLevelClient = RestHighLevelClientFactory.getRestHighLevelClient(host, port);
        String spuid = new String(message.getBody());
        Goods goods = spuService.findGoodsById(spuid);
        List<Sku> skuList = goods.getSkuList();
        try {
            for (Sku sku : skuList) {
                DeleteRequest deleteRequest = new DeleteRequest("sku", "doc", sku.getId());
                DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
                int status = response.status().getStatus();
                System.out.println(status);
            }
            restHighLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
